package com.store.app.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.recordBean_hy;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.OpenTaoBaoApp;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.widget.BookedOnlinePopupWindow;
import com.store.app.widget.ProgressWebView;
import com.store.app.widget.ShareDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 领了么详情页面
 */
public class FreeDetailsWebViewActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnClickListener ,IOnHttpListener{
    private TextView tv, tv_right;
    private ProgressWebView webView;
    private String title;
    private String urls = "", id = "";
    private LinearLayout lin_right;
    private ProgressBar progressBar;
    private SwipeRefreshLayout mSwipeLayout;
    private LinearLayout lin_all;
    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private BookedOnlinePopupWindow bp_online;
    private PopupWindow mPop;
    private final int POST_SUCC = 8;
    private final int POST_FAIL = 9;
    private String errorMsg;
    private GoToLogin goToLogin;

    private UMImage image;//分享时候的图标
    private String shareTitle;//分享标题
    private String shareText;//分享内容
    private String shareUrl;//分享链接
    private String sharePic;//分享图片
    private ShareDialog mShareDialog;//分享时候的弹窗
    private UMShareAPI mShareAPI;
    private View tv_Right1;//此页面当分享按钮

    private NetRequest mNetRequest;

    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case POST_SUCC:
                    dismissProgressDialog();
                    Toast.makeText(FreeDetailsWebViewActivity.this, "您的订单已提交，供应商将安排工作人员在24小时内确认订单并协商配送事宜，谢谢合作。", Toast.LENGTH_LONG).show();
                    break;
                case POST_FAIL:
                    dismissProgressDialog();
                    if (!TextUtils.isEmpty(errorMsg)) {
                        Toast.makeText(FreeDetailsWebViewActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                    }

                    break;
            }
        }
    };


    public FreeDetailsWebViewActivity() {
        super();
    }

    private String from = "";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_webview);
        mNetRequest = new NetRequest(this);

        urls = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        try {
            from = getIntent().getStringExtra("from");
        } catch (Exception e) {
            from = "";
        }
        goToLogin = new GoToLogin(this);

        findViews();
        setWebView();
        if(db==null){
            db=new DBHelper_hy(this);
            rb=new recordBean_hy();
        }
    }


    private void setWebView() {
        webView.clearCache(true);
        webView.loadUrl(urls);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置不使用缓存
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.setWebViewClient(new WebViewClient1());
        webView.setWebChromeClient(new WebChromeClient1());
        webView.addJavascriptInterface(new JSInterface(), "jsObj");


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_right:
               // finish();
                break;
            case R.id.tv_right1:

                break;
            case R.id.public_tv_right:
                mShareDialog = new ShareDialog(FreeDetailsWebViewActivity.this, listener);
                mShareDialog.show();
                break;
        }
    }

    private String mTaoBaoName;//JS方法名，通过此方法将数据传递到JS中

    final class JSInterface {

        private Handler handler = new Handler();

//        @JavascriptInterface
//        public void getTaobaoMemberName(final String name) {
//            handler.post(new Runnable() {
//                @Override
//                public void run() {
//                   Log.v("zyl","taobao:"+name);
//                }
//            });
//        }
        @JavascriptInterface
        public void storeGetFreeSucc() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "店东领取成功，跳转到订单页面");
                    Intent intent = new Intent(FreeDetailsWebViewActivity.this, TheSingleOrderActivity.class);
                    intent.putExtra("showFragmentIndex", "2");//2代表免费领样的Fragment
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void scan(final String string) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "scan:" + string);
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        String goods_code = jsonObject.getString("goods_code");
                        String goods_url = jsonObject.getString("goods_url");
                        String amount = jsonObject.getString("amount");
                        Intent intent = new Intent(FreeDetailsWebViewActivity.this, FreeScanActivity.class);
                        intent.putExtra("goods_code", goods_code);
                        intent.putExtra("goods_url", goods_url);
                        intent.putExtra("amount", amount);
                        startActivity(intent);
                    } catch (Exception e) {
                    }
                }

            });
        }

        @JavascriptInterface
        public void openTaobao(final String taokouling) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "获取淘口令：" + taokouling);
                    OpenTaoBaoApp.open(getApplicationContext(), taokouling);

                }
            }, 0);
        }

        @JavascriptInterface
        public void share(final String shareContent) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "分享的内容：" + shareContent);
                    try {
                        JSONObject jsonObject = new JSONObject(shareContent);
                        shareTitle = jsonObject.getString("title");
                        shareText = jsonObject.getString("desc");
                        String imgPath = jsonObject.getString("imgPath");
                        image = new UMImage(FreeDetailsWebViewActivity.this, imgPath);
                        Log.v("zyl", "shareUrl:" + shareUrl);
                        shareUrl = jsonObject.getString("url");
                    } catch (Exception e) {
                    }

                }
            }, 0);
        }


        @JavascriptInterface
        public void chatWithCustomerServiceAgent(final  String chat){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject=new JSONObject(chat);
                        String chatid=jsonObject.getString("chat_id");
                        String title=jsonObject.getString("title");
                        String hand=jsonObject.getString("head_pic_path");
                        Log.v("zyl","chatid:"+chatid);
                        Intent intent = new Intent(FreeDetailsWebViewActivity.this, ChatActivity.class);
                        intent.putExtra("userId", chatid);
                        intent.putExtra("groupName", title);
                        startActivity(intent);

                        try {
                            rb.saveMember(db, "", chatid, title
                                    , "",hand, "0");
                        }catch (Exception e){
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, 0);
        }
        //打开广告页
        @JavascriptInterface
        public void openAdLayer(final String jsonData) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.v("zyl", "openAdLayer jsonData:" + jsonData);
                    try {
                        JSONObject jsonObject = new JSONObject(jsonData);
                        String url = jsonObject.getString("url");
                        Intent intent = new Intent(FreeDetailsWebViewActivity.this, WebViewAdActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            });
        }

        //获取淘宝会员名
        @JavascriptInterface
        public void getTaobaoMemberName(String taoBaoName) {

            mTaoBaoName = taoBaoName;

            handler.post(new Runnable() {
                @Override
                public void run() {

                    try {
                        //查询SP，判断是否有绑定淘宝会员名
                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(FreeDetailsWebViewActivity.this);
                        String account_id = preferences.getString("account_id", "notQuery");

                        if("notQuery".equals(account_id)){
                            //登陆时未来得及查询，应再次查询
                            if(!TextUtils.isEmpty(MainActivity.member_id)){
                                mNetRequest.requestQueryTaoBao(2, MainActivity.member_id, SettingData.STORES);
                            }

                        }else {
                            String account_no = preferences.getString("account_no", "");
                            JSONObject taoBaoJsonObject = new JSONObject();
                            taoBaoJsonObject.put("account_id",account_id);
                            taoBaoJsonObject.put("account_no",account_no);
                            String tempData = "'"+taoBaoJsonObject.toString()+"'";
                            webView.loadUrl("javascript:" + mTaoBaoName + "(" + tempData + ")");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });

        }

        //跳转到绑定淘宝用户名界面
        @JavascriptInterface
        public void bindTaobaoMemberName() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(FreeDetailsWebViewActivity.this, BindTaoBaoAccountActivity.class);
                    intent.putExtra("startActivity",SetActivity.class.getSimpleName());
                    startActivity(intent);
                }
            });

        }

    }

    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络!");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.d("xgp", "领了么详情 querySuccess:" + result);
        try {
            //解析服务器返回的用户绑定的淘宝账户信息
            JSONObject jsonObject = new JSONObject(result);
            JSONArray taoBaojsonArray = jsonObject.getJSONArray("list");
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = preferences.edit();

            if(taoBaojsonArray.length() == 0){
                editor.putString("account_id","").apply();
                editor.putString("account_no","").apply();
            }else{
                JSONObject taoBaojsonObject = taoBaojsonArray.getJSONObject(0);
                String account_id = taoBaojsonObject.getString("account_id");
                String account_no = taoBaojsonObject.getString("account_no");
                Log.d("xgp", "account_id:" + account_id);
                Log.d("xgp", "account_no:" + account_no);
                //将用户绑定的淘宝账户信息存储到SP文件中
                editor.putString("account_id",account_id).apply();
                editor.putString("account_no",account_no).apply();
            }

            String account_id = preferences.getString("account_id", "");
            String account_no = preferences.getString("account_no", "");

            JSONObject taoBaoJsonObject = new JSONObject();
            taoBaoJsonObject.put("account_id",account_id);
            taoBaoJsonObject.put("account_no",account_no);
            String tempData = "'"+taoBaoJsonObject.toString()+"'";
            webView.loadUrl("javascript:" + mTaoBaoName + "(" + tempData + ")");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showToast(msg);
    }

    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    public class WebViewClient1 extends android.webkit.WebViewClient {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {                 // Handle the error
            Log.v("zyl", "onReceivedError网络加载不出来");
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
//			lin_loadfail.setVisibility(View.VISIBLE);
            showLoadResult(1);
//			Toast.makeText(WebViewBookedActivity.this,"description:"+description,Toast.LENGTH_SHORT).show();
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            } catch (Exception e) {

            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.v("zyl", "onPageStart:" + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.startsWith("http")) {
                urls = url;
            }
        }

    }

    public class WebChromeClient1 extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.v("zyl", "加载进度：" + newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                if (progressBar.getVisibility() == View.GONE)
                    progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    public void onPause() {//继承自Activity
        super.onPause();
//        webView.onPause();
//        webView.pauseTimers();
        if (isFinishing()) {
            Log.v("zyl", "isFinishing");
            webView.loadUrl("about:blank");
            setContentView(new FrameLayout(this));
        }
    }

    public void onResume() {//继承自Activity
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    private void findViews() {
        tv_Right1 = findViewById(R.id.tv_right1);
        tv_Right1.setOnClickListener(this);
        lin_right = (LinearLayout) findViewById(R.id.public_ll_right);
        lin_right.setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.public_tv_right);
//        tv_right.setText("关闭");
        tv_right.setBackgroundResource(R.drawable.pic_icon_share);
        tv_right.setOnClickListener(this);
//        tv_Right1.setVisibility(View.VISIBLE);
//        tv_Right1.setBackgroundResource(R.drawable.pic_icon_share);

        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                showLoadResult(3);
                webView.clearCache(true);
                webView.clearHistory();
                webView.clearFormData();
                webView.loadUrl(urls);
            }
        });
        lin_all = (LinearLayout) findViewById(R.id.lin_all);
        webView = (ProgressWebView) findViewById(R.id.onlcon_web);
        webView.setContext(this);

        tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText(title);
        findViewById(R.id.public_ll_return).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
            }
        });
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
        mSwipeLayout.setOnRefreshListener(this);

        mShareAPI = UMShareAPI.get(this);

        shareTitle = "";
        shareText = "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !"about:blank".equals(webView.getUrl())) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        setWebView();
        mSwipeLayout.setRefreshing(false);
    }

    ShareDialog.OnShareClickListener listener = new ShareDialog.OnShareClickListener() {
        @Override
        public void FriendCircle(View v) {
            new ShareAction(FreeDetailsWebViewActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void WeChatFriends(View v) {
            new ShareAction(FreeDetailsWebViewActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)

                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void QQFriends(View v) {
            new ShareAction(FreeDetailsWebViewActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)
                    .share();
            mShareDialog.dismiss();

        }

        @Override
        public void QQZone(View v) {
            new ShareAction(FreeDetailsWebViewActivity.this).setPlatform(SHARE_MEDIA.QZONE).setCallback(umShareListener)
                    .withTitle(shareTitle)
                    .withMedia(image)
                    .withText(shareText)
                    .withTargetUrl(shareUrl)

                    .share();
            mShareDialog.dismiss();
        }

        @Override
        public void Copy(View v) {

        }

        @Override
        public void SMS(View v) {

        }


        @Override
        public void Email(View v) {
        }
    };
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(FreeDetailsWebViewActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(FreeDetailsWebViewActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
            if(t != null){
                Log.d("xgp","分享失败原因：" + t.getMessage());
            }
    }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        mShareAPI.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
